'use strict';

const BaseService = require('./base');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');

class MemberService extends BaseService {
  constructor(ctx) {
    super(ctx, 'Member');
  }

  // 加密密码
  hashPassword(password) {
    return crypto.createHash('sha256').update(password).digest('hex');
  }

  // 生成JWT token
  generateToken(member) {
    const { app } = this.ctx;
    const { id, phone } = member;
    return jwt.sign({ id, phone }, app.config.jwt.secret, {
      expiresIn: '7d', // token有效期7天
    });
  }

  // 注册
  async register(data) {
    const { ctx } = this;
    const { phone, password, nickname } = data;

    // 检查手机号是否已注册
    const exists = await ctx.model.Member.findOne({ where: { phone } });
    if (exists) {
      ctx.throw(400, '该手机号已注册');
    }

    // 创建会员
    const member = await ctx.model.Member.create({
      phone,
      password: this.hashPassword(password),
      nickname: nickname || `用户${phone.substr(-4)}`, // 如果没有昵称，使用手机号后4位
      status: 1,
    });

    // 生成token
    const token = this.generateToken(member);

    return {
      token,
      member: {
        id: member.id,
        phone: member.phone,
        nickname: member.nickname,
        avatar: member.avatar,
      },
    };
  }

  // 登录
  async login(data) {
    const { ctx } = this;
    const { phone, password } = data;

    // 查找会员
    const member = await ctx.model.Member.findOne({ where: { phone } });
    if (!member) {
      ctx.throw(400, '账号或密码错误');
    }

    // 验证密码
    if (this.hashPassword(password) !== member.password) {
      ctx.throw(400, '账号或密码错误');
    }

    // 检查账号状态
    if (member.status !== 1) {
      ctx.throw(403, '账号已被禁用');
    }

    // 生成token
    const token = this.generateToken(member);

    return {
      token,
      member: {
        id: member.id,
        phone: member.phone,
        nickname: member.nickname,
        avatar: member.avatar,
      },
    };
  }

  // 修改密码
  async changePassword(memberId, data) {
    const { ctx } = this;
    const { oldPassword, newPassword } = data;

    // 查找会员
    const member = await ctx.model.Member.findByPk(memberId);
    if (!member) {
      ctx.throw(404, '会员不存在');
    }

    // 验证旧密码
    if (this.hashPassword(oldPassword) !== member.password) {
      ctx.throw(400, '原密码错误');
    }

    // 更新密码
    await member.update({
      password: this.hashPassword(newPassword),
    });

    return true;
  }

  // 重置密码（通过手机验证码）
  async resetPassword(data) {
    const { ctx } = this;
    const { phone, code, newPassword } = data;

    // TODO: 验证手机验证码
    // await ctx.service.sms.verifyCode(phone, code);

    // 查找会员
    const member = await ctx.model.Member.findOne({ where: { phone } });
    if (!member) {
      ctx.throw(404, '会员不存在');
    }

    // 更新密码
    await member.update({
      password: this.hashPassword(newPassword),
    });

    return true;
  }

  // 根据手机号查找会员
  async findByPhone(phone) {
    const { app } = this.ctx;
    return await app.model.Member.findOne({
      where: { 
        phone,
        status: 1
      }
    });
  }

  // 根据openid查找会员
  async findByOpenid(openid) {
    const { app } = this.ctx;
    return await app.model.Member.findOne({
      where: { 
        openid,
        status: 1
      }
    });
  }

  // 重写getPage方法，支持按手机号和昵称搜索
  async getPage(where, page, pageSize) {
    return super.getPage(where, page, pageSize);
  }

  // 检查用户是否是会员
  async checkMember(userId) {
    const { app } = this.ctx;
    const member = await app.model.Member.findOne({
      where: {
        userId,
        status: 1,
        expireTime: {
          $gt: new Date()
        }
      }
    });
    return !!member;
  }
}

module.exports = MemberService;
